package com.ls.server.service.impl;

import com.ls.server.domain.ChatModel;
import com.ls.server.service.ChatModelService;
import com.ls.server.service.ChatService;
import com.ls.server.service.model.strategy.ChatModelStrategy;
import com.ls.server.service.model.strategy.ChatModelStrategyFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.Map;

/**
 * 聊天服务实现类
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {

    private final ChatModelService chatModelService;
    private final ChatModelStrategyFactory strategyFactory;

    /**
     * 发送聊天请求（同步）
     *
     * @param modelId 模型ID
     * @param prompt 提示词
     * @param options 选项
     * @return 回复内容
     */
    @Override
    public String chat(Long modelId, String prompt, Map<String, Object> options) {
        // 获取模型信息
        ChatModel model = chatModelService.getById(modelId);
        if (model == null) {
            throw new RuntimeException("模型不存在");
        }

        // 检查模型状态
        if (!model.getEnabled()) {
            throw new RuntimeException("模型已禁用");
        }

        try {
            // 获取策略
            ChatModelStrategy strategy = strategyFactory.getStrategy(model.getModelContext());

            // 发送请求
            return strategy.chat(modelId, prompt, options);
        } catch (Exception e) {
            log.error("聊天请求失败", e);
            return "聊天请求失败：" + e.getMessage();
        }
    }

    /**
     * 发送聊天请求（异步流式）
     *
     * @param modelId 模型ID
     * @param prompt 提示词
     * @param options 选项
     * @return 回复内容流
     */
    @Override
    public Flux<String> chatStream(Long modelId, String prompt, Map<String, Object> options) {
        // 获取模型信息
        ChatModel model = chatModelService.getById(modelId);
        if (model == null) {
            return Flux.error(new RuntimeException("模型不存在"));
        }

        // 检查模型状态
        if (!model.getEnabled()) {
            return Flux.error(new RuntimeException("模型已禁用"));
        }

        try {
            // 获取策略
            ChatModelStrategy strategy = strategyFactory.getStrategy(model.getModelContext());

            // 发送请求
            return strategy.chatStream(modelId, prompt, options);
        } catch (Exception e) {
            log.error("聊天流式请求失败", e);
            return Flux.error(e);
        }
    }
}
